//
//  CatagoryInsideViewController.m
//  GiftSay
//
//  Created by laohu on 16/1/11.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "CatagoryInsideViewController.h"
#import "HXInsideLongCell.h"
#import "HomeNewModel.h"
#import "WebViewController.h"

@interface CatagoryInsideViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, copy) NSString *next_url;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, assign) CGFloat contentY;
@property (nonatomic, assign) int scrollTimes;
@property (nonatomic, assign) NSInteger *arrayCount;
@end

@implementation CatagoryInsideViewController


- (void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        self.navigationController.navigationBar.barTintColor = kNightModeNavigationColor;
    } else {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:248 / 255.0 green:78 / 255.0 blue:78 / 255.0 alpha:1];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    [self getData:self.url];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"NightModeOpen" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"NightModeOff" object:nil];
    self.navigationItem.title = self.model.name;
    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backToCatagory:)];
    self.navigationItem.leftBarButtonItem = button;
    self.navigationItem.rightBarButtonItem = nil;
    
}
- (void)refresh {
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        self.tableView.backgroundColor = kNightModeColor;
    } else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    [self.tableView reloadData];
}
- (void)setModel:(HXCatagorySecondModel *)model {
    _model = model;

    self.url = [NSString stringWithFormat:kCatagoryItem, model.ids];
//    NSLog(@"%@", self.url);
}
- (void)backToCatagory:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)createView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 49) style:UITableViewStyleGrouped];
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        self.tableView.backgroundColor = kNightModeColor;
    } else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[HXInsideLongCell class] forCellReuseIdentifier:@"CatagoryItem"];
    [self.view addSubview:_tableView];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HXInsideLongCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatagoryItem"];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (self.view.height - 40) / 3;
}
#pragma mark - 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    //webview网址  不到哪个
//    [self.dataSource[indexPath.row] content_url];
//    [self.dataSource[indexPath.row] url];
    WebViewController *web = [[WebViewController alloc] init];
//    NSLog(@"%@", [self.dataSource[indexPath.row] content_url]);

    web.nameFromTactik = [self.dataSource[indexPath.row] title];

    web.type = @"post";
    web.url = [NSString stringWithFormat:@"%@%@", kPostInfo, [self.dataSource[indexPath.row] ids]];
    [self.navigationController pushViewController:web animated:NO];
}

#pragma mark - 上拉加载
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.contentY = scrollView.contentOffset.y;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.contentY) {
        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
//            NSLog(@"%d", self.scrollTimes);
//            NSLog(@"🐱%d", self.scrollTimes);
            //加载更多数据
            if (self.scrollTimes == 0) {
                self.arrayCount = self.arrayCount + 20;
                [self getData:self.next_url];
                self.scrollTimes = 1;
//                NSLog(@"%@", self.url);
//                NSLog(@"%@", self.next_url);
            }
            
        }
    }
}


- (void)getData:(NSString *)url {
    [LYKNetWorkTool getWithUrl:url parameter:nil httpHeader:nil resposeType:ResponseTypeJSON success:^(id(success)) {
//        NSLog(@"%@", success);
        NSDictionary *dic = success[@"data"];
        NSArray *array = dic[@"items"];
//        NSLog(@"%@", dic);
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dictionary in array) {
            HomeNewModel *model = [[HomeNewModel alloc] init];
            [model setValuesForKeysWithDictionary:dictionary];
            [arr addObject:model];
        }
//        self.dataSource = [NSMutableArray arrayWithArray:arr];
        
//        self.next_url = paging[@"next_url"];
        if (!self.dataSource) {
            NSDictionary *paging = dic[@"paging"];
            self.dataSource = [NSMutableArray arrayWithArray:arr];
            self.next_url = paging[@"next_url"];
        } else {
            [self.dataSource addObjectsFromArray:arr];
            NSDictionary *paging = dic[@"paging"];
            self.next_url = paging[@"next_url"];
            
            
        }

        
        if (self.dataSource.count > 0) {
            if (!self.tableView) {
                [self createView];
            }
            
        }
        
        
        self.scrollTimes = 0;
        [self.tableView reloadData];
//        NSLog(@"🐶%d", self.scrollTimes);
        
//        NSLog(@"%@", self.dataSource);
    } fail:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
